#' ---
#' title: "Replication Adaptive Parties Main Text"
#' author: "Lukas Stoetzer & Tarik Abou-Chadi"
#' date: "23 February 2020"
#' ---

#+ start, echo=FALSE, include=FALSE, message=FALSE, warning=FALSE
# Packages
  library(texreg)
  library(ggplot2)
  library(MASS)

  source("fun_panel.R")

# Read Data
  load("pty_dat_wweights.Rdata")
  
#' ## Main Results: Conditional Effects Left-Right Positions
#+ models, echo=FALSE

 # Models with rile
  m1 <- lm(rile ~ 1 +  rile_lag + wlp_rile + avg_rile_shift_lag + countryname, data=DT)

  DT$pervote_diff_lag_cut <-  cut(x = DT$pervote_diff_lag_rel, quantile(DT$pervote_diff_lag_rel,c(0,.33,1),na.rm=T))
  levels(DT$pervote_diff_lag_cut)  <- c("low","high")
  
  m3 <- lm(rile ~ 1 +  rile_lag + wlp_rile*pervote_diff_lag_cut  + countryname + avg_rile_shift_lag, data=DT)
  models <- list(m1,m3)
  
  robust_se <- lapply(models, double_clustered_se)
  robust_p <- lapply(models, double_clustered_se, get="Pr(>|t|)")

#+ table_main, results='asis', echo=FALSE
  texreg(models,  
         omit.coef=c("(countryname|party)"),
         override.se=robust_se,override.pvalues=robust_p
         ,custom.coef.map = list(
           'wlp_rile' =  '$W_{Losses}$ Rile',
           'wlp_logrile' =  '$W_{Losses}$ Rile',
           'wls_rile' =  '$W_{Losses}$ Rile',
           "wd_rile" = '$W_{Distance}$ Rile',
           'rile_lag' =  'Rile (t-1)',
           'logrile_lag' =  'Rile (t-1)',
           'pervote_diff_lag_rel' = 'Vote Change (t-1)',
           'wlp_rile:pervote_diff_lag_rel' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1)',
           'wlp_logrile:pervote_diff_lag_rel' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1)',
           'wls_rile:pervote_diff_lag_rel' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1)',
           'wlp_rile:pervote_diff_lag_cutmid' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1) midle 50 \\%',
           'wlp_rile:pervote_diff_lag_cuthigh' = '$W_{Losses}$ Rile $\\times$ \\\\ Vote Change (t-1) highest 66 \\%',
           'wlp_logrile:pervote_diff_lag_cutmid' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1) midle 50 \\%',
           'wlp_logrile:pervote_diff_lag_cuthigh' = '$W_{Losses}$ Rile $\\times$ \\\\ Vote Change (t-1) highest 66 \\%',
           'pervote_diff_lag_cutmid:wls_rile' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1) midle 50 \\%',
           'pervote_diff_lag_cuthigh:wls_rile' = '$W_{Losses}$ Rile $\\times$ \\\\ Vote Change (t-1) highest 25 \\%',
           'pervote_diff_lag_cutlow' = 'Vote Change (t-1) lowest 33 \\\\% ',
           'pervote_diff_lag_cuthigh' = 'Vote Change (t-1) highest 66 \\\\%',
           "avg_rile_shift_lag" = "Avg. Rile Shift (t-1)",
           'avg_rile_lag' = 'Av. Left-Right (t-1)',
           'avg_logrile_lag' = 'Av. Left-Right (t-1)',
           "median_voter_lag" = "Median voter (t-1)",
           "median_voter_logrile_lag" = "Median voter (t-1)"
         ),
         label = "tab:main",float.pos="t",stars = c(0.1,0.05, 0.01),
         #custom.model.names = c("\\makecell{Model 1 \\\\ Rile}","\\makecell{Model 2 \\\\ Rile}"),
         caption = "The reaction of parties to voter transtions. The table shows the results of spatial lag models estimted with OLS. 
         The dependent variable of the model is the rile index from the Party Manifesto. Each specifcation includes country-fixed effects that are exluded from the table.",
         #booktabs = T, dcolumn = T,use.packages = F, 
         scalebox = 0.9
  )
  


#+ figure_main_alt_code, echo=FALSE
  
  # Sampling distribution
  S1 <- mvrnorm(10000,coef(m3),vcov(m3))
  
  # Marginal Effect of Party Position B on Party Position A
  
  # Create Different Scenarios for movement of other party and transtiions
  matS <- S1[,c("wlp_rile","wlp_rile:pervote_diff_lag_cuthigh")]
  
  # Get Scenarios
  other_pty_lr <- 25
  voter_transtions <- c(0.05,0.15,0.35)
  Xlr <- expand.grid(other_pty_lr*voter_transtions, c(1,0))
  Xlr$Var2 <- Xlr$Var1 * Xlr$Var2
 
    
  # Calculate Expected Values
  evlr <- matS %*% t(Xlr)
  evlr_qi <- t(apply(evlr,2,quantile,c(0.01,0.025,0.5,0.975,0.99)))
  
  
  # Preapre Data-frame
  lab_y <- paste(100*as.numeric(voter_transtions), "% net transfers A to B", sep="")
  lab_vl <- c("Party A lost less than 5.8% or won votes","Party A lost more than 5.8%")
  model <- c(rep("Left-Right Shift",length(voter_transtions)))
  vote_loss <- as.factor(sort(rep(lab_vl,length(voter_transtions))))
  df <- data.frame(cbind(evlr_qi,voter_transtions),"vote_loss" = vote_loss,"time"="Election","party"="Party A")
  names(df) <- c("low2","low","mid","high","high2","voter_transtions","vote_loss","time","party")
  df$type <- lab_y
  
  n_trans <- length(voter_transtions)
  df_pos <- data.frame("mid"=c(rep(other_pty_lr,2*n_trans)),
                       "low"=c(rep(other_pty_lr,2*n_trans)),
                       "high"=c(rep(other_pty_lr,2*n_trans)),
                       "low2"=c(rep(other_pty_lr,2*n_trans)),
                       "high2"=c(rep(other_pty_lr,2*n_trans)),
                       "time"=as.factor(c(rep("Election",2*n_trans))),
                       "party"=as.factor(c(rep("Party B",2*n_trans))),
                       "vote_loss"=as.factor(sort(rep(lab_vl,n_trans))))
  
  df_pos$voter_transtions <- c(voter_transtions)
  df_pos$type <- lab_y
  

  #+ simplot2, fig.width=12
  df <- rbind(df_pos[,colnames(df)],df)
  df$type <- factor(df$type, levels = lab_y)
  df$party <- relevel(df$party,"Party A")
  
  ggplot() +
    geom_pointrange(data=df,
                    aes(y=mid,ymin=low,ymax=high,x=as.factor(1), col=(party))
                    ,size=1.5) +
    geom_vline(xintercept = 1, size=0.3, alpha=0.3) +
    geom_hline(yintercept = 0, size=0.3, alpha=0.3, col="red") +
    ylim(c(-8,27)) + coord_flip() + facet_grid(type ~ vote_loss, switch = "y") +
    xlab("") + ylab("")  +
    theme(panel.grid.major = element_blank(),
          panel.grid.minor = element_blank(),
          panel.background = element_blank(),
          strip.background = element_blank(),
          # strip.text.y = element_blank(),
          axis.text.y=element_blank(),
          legend.position = "top",
          text = element_text(size=20),
          legend.title=element_blank(),
          strip.text.y = element_text(angle = 180),
          axis.ticks.y=element_blank()) +
    scale_color_grey()
